package myJs.user.data

import myJs.Implicits._
import myJs.Utils.layer
import myJs.Utils
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scalatags.Text.all._

/**
 * Created by yz on 16/9/2021
 */
@JSExportTopLevel("LoadData")
object LoadData {

  @JSExport("init")
  def init = {
    Tool.fileInput
    bootStrapValidator
    registerEvent
  }

  def registerEvent = {
    $(document.body).on("click", s".myRun", "", (y: Element) => {
      myRun
    })
    $(document.body).on("change fileclear", s".file", "", (y: Element) => {
      $(y).parents("form").bv.revalidateField("file")
    })
  }

  def myRun = {
    val formJq = $("#form")
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val element = div(id := "content",
        span(id := "info", "文件上传中",
          span(id := "progress")), " ",
        img(src := "/assets/images/running2.gif", cls := "runningImage", width := 30, height := 20)
      ).render
      val layerOptions = LayerOptions.icon(16).shade(0.01).time(20000000)
      val index = layer.msg(element, layerOptions)
      val formData = new FormData(formJq(0).toHTMLFormElement)
      val url = g.jsRoutes.controllers.DataController.loadData().url.toString
      val xhr = new XMLHttpRequest
      xhr.open("post", url)
      xhr.upload.onprogress = Utils.progressHandlingFunction
      xhr.onreadystatechange = (e) => {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          val rs = xhr.responseText.toJDJAn
          layer.close(index)
          val valid = rs("valid").toB
          if (valid) {
            Swal.swal(SwalOptions.title("成功").text("导入数据成功!").`type`("success"))
            val url=g.jsRoutes.controllers.DataController.sampleManage().url.toString
            window.location.href=url
          } else {
            g.swal("Error", rs.myGet("message"), "error")
          }
        }
      }
      xhr.send(formData)
    }
  }

  def bootStrapValidator = {
    val url = g.jsRoutes.controllers.DataController.sampleNameCheck().url.toString
    val maxNumber = Double.MaxValue
    val dict: js.Dictionary[js.Any] = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> js.Dictionary(
        "sampleName" -> {
          val info = "文件名"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "remote" -> js.Dictionary(
                "message" -> s"${info}已存在！",
                "url" -> url,
                "delay" -> 1000,
                "type" -> "POST",
              ),
            )
          )
        },
        "describe" -> {
          val info = "描述"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
            )
          )
        },
        "file" -> {
          val info = "序列文件"
          js.Dictionary(
            "validators" -> js.Dictionary(
              "notEmpty" -> js.Dictionary(
                "message" -> s"${info}不能为空！"
              ),
              "file" -> js.Dictionary(
                "message" -> s"${info}格式不正确（*.fa,*.fasta）！",
                "extension" -> "fa,fasta",
              ),

            )
          )
        },
      )
    )
    $(s"#form").bootstrapValidator(dict)
  }


}
